const ratelimit = require("koa-ratelimit");
const db = new Map();
function getClientIP(ctx) {
  let ip =
    ctx.req.headers["x-forwarded-for"] || // 判断是否有反向代理 IP
    ctx.req.ip ||
    ctx.req.connection.remoteAddress || // 判断 connection 的远程 IP
    ctx.req.socket.remoteAddress || // 判断后端的 socket 的 IP
    ctx.req.connection.socket.remoteAddress ||
    "";
  if (ip) {
    ip = ip.replace("::ffff:", "");
  }
  return ip;
}

module.exports = function (app) {
  app.use(
    ratelimit({
      driver: "memory",
      db: db,
      duration: 10000,
      errorMessage: "请求过于频繁",
      id: (ctx) => ctx.ip,
      headers: {
        remaining: "Rate-Limit-Remaining",
        reset: "Rate-Limit-Reset",
        total: "Rate-Limit-Total",
      },
      max: 10,
      disableHeader: false,
      whitelist: (ctx) => {
        // console.log(db, "white");
      },
      blacklist: (ctx) => {
        // console.log(ctx, "white");
      },
    })
  );
};
